//
//  NSStringFormat.m
//  OpensslTest
//
//  Created by jiahua on 16/3/28.
//  Copyright © 2016年 secsmarts. All rights reserved.
//

#import "sstNSStringFormat.h"

@implementation sstNSStringFormat

+(u8*)NSString2Char:(NSString *)str{
    NSData* data = [sstNSStringFormat NSString2NSData:str];
    u8* content = (u8*)[data bytes];
    return content;
}

+(NSString*)Char2NSString:(u8 *)str{
    NSString* nsStr = [[NSString alloc] initWithCString:(const char *) str encoding:NSUTF8StringEncoding];
    return nsStr;
}

+(NSData *)NSString2NSData:(NSString *)str{
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}

+(NSString *)Byte2HexNSString:(Byte *)byte withLength: (NSUInteger)len {
    NSString * returnString = @"";

    for(int i=0;i<len;i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",byte[i]&0xff];///16进制数
        if([newHexStr length] == 1)
            returnString = [NSString stringWithFormat:@"%@0%@",returnString,newHexStr];
        else
            returnString = [NSString stringWithFormat:@"%@%@",returnString,newHexStr];
    }
    return returnString;
}

+(int)CharToByte: (const u8 *)inBuf withLen: (int) inLen outBuf: (u8 *)outBuf
{
    if(inLen%2 != 0)
    {
        return -1;
    }
    
    for(int i = 0; i < inLen; i += 2)
    {
        char temp = 0;
        
        if(inBuf[i] >= 'A' && inBuf[i] <= 'Z')
        {
            temp = inBuf[i] - 'A' + 10;
        }
        else if(inBuf[i] >= 'a' && inBuf[i] <= 'z')
        {
            temp = inBuf[i] - 'a' + 10;
        }
        else if(inBuf[i] >= '0' && inBuf[i] <= '9')
        {
            temp = inBuf[i] - '0';
        }
        else
        {
            temp = 0;
        }
        
        if(inBuf[i+1] >= 'A' && inBuf[i+1] <= 'Z')
        {
            temp =(temp << 4) |  inBuf[i+1] - 'A' + 10;
        }
        else if(inBuf[i+1] >= 'a' && inBuf[i+1] <= 'z')
        {
            temp = (temp << 4) | inBuf[i+1] - 'a' + 10;
        }
        else if(inBuf[i+1] >= '0' && inBuf[i+1] <= '9')
        {
            temp = (temp << 4) | inBuf[i+1] - '0';
        }
        else
        {
            temp = (temp << 4) |  0;
        }
        
        outBuf[i/2] = temp;
    }
    
    return 0;
}

@end
